<template>
  <!--月度汇总-->
  <div class="full-size month-sum table-container">
    <BasicTable @register="registerTable" v-show="init">
      <template #tableTop>
        <div class="weight-hint">
          <p class="hint_title">说明</p>
          <ul class="hit_ul">
            <li>汇总成功后，请到月度监控中查看班组汇总状态</li>
            <li>考核分数说明：80（100）代表汇总分为100，折算后分数为80</li>
            <li>
              折算方式算法：
              <!-- <p> 标杆法：[基础分+（100-基础分）*（个人积分/标杆值）]*80%</p> -->
              <p> 平均分标杆：个人积分/标杆值 *100 （说明：其中标杆值 = 平均分）</p>
              <p> 最高分分标杆：个人积分/标杆值 *100 （说明：其中标杆值 = 最高分）</p>
              <p> 差值法：100 * [k+（1-k）(本人积分-最低分)/(最高-最低)]</p>
            </li>
          </ul>
        </div>
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleInit" :disabled="canSum"> 汇总</a-button>
        <a-button type="primary" @click="handleUpdateStatus('submit')" :disabled="canSubmit"> 提交</a-button>
        <a-button type="primary" @click="handleUpdateStatus('release')">发布</a-button>
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="() => onExportXls()">导出</a-button>
        <a-button type="primary" @click="handleUpdateStatus('pass')">审核通过</a-button>
        <a-button type="primary" @click="handleUpdateStatus('reject')">退回</a-button>
        <a-button preIcon="ant-design:edit-outlined" @click="batchEdit" v-if="!startEdit" :disabled="editDisable"> 批量编辑</a-button>
        <a-button type="primary" preIcon="ant-design:save-outlined" @click="batchSave" v-if="startEdit"> 保存</a-button>
        <a-button preIcon="ant-design:close-outlined" @click="editCancel" v-if="startEdit"> 取消</a-button>
      </template>

      <template #bodyCell="{ column, text, record }">
        <template v-if="column.editComponent">
          <a-select style="width: 100%" v-if="'Select' === column.editComponent && startEdit" v-model:value="record[column.dataIndex]" :options="dictOptions" />
          <span v-if="!startEdit" :title="text"> {{ text }} </span>
        </template>
      </template>
    </BasicTable>
    <detail-modal @register="registerModal" />
  </div>
</template>

<script setup name="HubTeamResultSummarizing">
import { ref, onMounted, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent, onActivated, onDeactivated } from 'vue';
import { BasicTable } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns, searchFormSchema } from './hubTeamResultSummarizing.data';
import { list, getColumn, batchUpdate, initSummary, publishSummary, handleCommit, getExportUrl, getImportUrl } from './service';
import { Modal } from 'ant-design-vue';
import { useModal } from '/@/components/Modal';
import { initDictOptions } from '/@/utils/dict/index';
import { useRoute } from 'vue-router';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

// 轻提醒
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage: $message } = useMessage();


// 列表页面公共参数、方法
const { tableContext, onExportXls } = useListPage({
  designScope: 'user-list',
  spinning: () => (spinning.value = !spinning.value),
  tableProps: {
    api: list,
    columns: columns,
    size: 'small',
    showActionColumn: false,
    indexColumnProps: {
      width: 40,
    },
    immediate: true,
    formConfig: {
      // labelWidth: 200,
      schemas: searchFormSchema,
    },
    beforeFetch: (params) => {
      canSubmit.value = false;
      canSum.value = false;
      editDisable.value = false;
      let { periodCode } = getForm().getFieldsValue();
      if (!periodCode) {
        periodCode = dayjs().format('YYYYMM');
      }
      return Object.assign(params, { pageSource: 'hz' });
    },
    afterFetch: (result) => {
      try {
        let data = result[0];
        if ('32' == data.status) {
          //已提交
          canSubmit.value = true;
          canSum.value = true;
        }
        if ('38' == data.status || '44' == data.status) {
          editDisable.value = true;
        }
      } catch (e) { }
    },
  },
  exportConfig: {
    name: '月度汇总',
    url: getExportUrl,
  },
  // importConfig: {
  //   url: getImportUrl,
  //   success: handleSuccess,
  // },
});
//注册table数据和方法
// eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
const [registerTable, { getForm, reload, getDataSource, setTableData, setColumns }, { rowSelection, selectedRowKeys }] = tableContext;


// 注册工分系数维护弹窗
const [registerModal, { openModal: openModal = () => { } }] = useModal();
const detailData = (record, dataIndex) => {
  openModal(true, { record, dataIndex });
};


initDictOptions('epm_result_grade').then((res) => {
  dictOptions.value = res;
});
let canSubmit = ref(false);
let editDisable = ref(false);
let canSum = ref(false);
let init = ref(true); //表格是否渲染
let spinning = ref(false);
let startEdit = ref(false);
let showEdit = ref(false); //是否显示编辑按钮 表头配置了动态平衡分时显示
let dictOptions = ref([]);
const route = useRoute();
let orgCode = null;
let periodCode = null;
let pageParams = {
  orgCodeBase: '',
  orgNameBase: '',
};
onActivated(() => {
  orgCode = route.params.orgCode;
  periodCode = route.params.periodCode;
  if (orgCode) {
    let form = getForm();
    pageParams.orgCodeBase = orgCode;
    form.setFieldsValue({ orgCode });
    if (periodCode) {
      form.setFieldsValue({ periodCode });
    }
    reload();
  }
});

onDeactivated(() => {
  localStorage.removeItem('orgCode');
  localStorage.removeItem('periodCode');
});

// 默认执行一次
const orgName = ref(userStore.getOrgName);
onMounted(async () => {
  let form = getForm();
  //获取编辑按钮的状态
  getTableColumn({ orgCode: userStore.getOrgCode });
  form.updateSchema([
    {
      field: 'periodCode',
      label: '考核周期',
      componentProps: {
        onChange: (e) => {
          handleSuccess();
        },
      },
    },
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e, i) => {
          orgName.value = i?.label;
          getTableColumn({ orgCode: e });
          setTableData([]);
          handleSuccess();
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
});

//查询动态表头
function getTableColumn() {
  let params = {
    orgCode: getForm().getFieldsValue().orgCode
  }
  getColumn(params)
    .then((res) => {
      let newColumn = [...columns];
      res.forEach((r) => {
        let temp = {
          title: r.headName,
          dataIndex: r.headCode,
          width: 200,
          align: 'center',
        };
        // 平衡系数
        if ('hortationScore' === r.headCode) {
          //temp.editRow = true;
          temp.editComponent = 'InputNumber';
          showEdit.value = true;
        }
        // 等级
        if ('grade' === r.headCode) {
          //temp.editRow = true;
          temp.editComponent = 'Select';
          showEdit.value = true;
        }
        newColumn.splice(newColumn.length - 2, 0, {
          ...temp,
          checkDetail: r.checkDetail, //判断是否能打开详情 boolean
          scopedSlots: { customRender: r.headCode },
        });
      });
      newColumn[newColumn.length - 2]['fixed'] = 'right';
      newColumn[newColumn.length - 1]['fixed'] = 'right';
      //重设表头
      nextTick(() => {
        setColumns(newColumn);
      });
    })
    .finally(() => {
      init.value = true;
    });
}

// 汇总
function handleUpdateStatus(type) {
  const msg = type == 'release' ? '确认发布吗?' : type == 'reject' ? '确认退回吗?' : type == 'pass' ? '确认审核通过吗?' : '确认提交吗?';
  const saveMsg = type == 'release' ? '发布' : type == 'reject' ? '退回' : '提交';
  let formData = getForm().getFieldsValue();
  const saveData = {
    orgCode: pageParams.orgCodeBase,
    periodCode: formData.periodCode,
    type: type,
  };
  Modal.confirm({
    content: msg,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      publishSummary(saveData).then((res) => {
        // console.log('res', res);
        if (res) {
          handleSuccess();
        }
      });
    },
    onCancel: () => {
      $message.info('已取消');
    },
  });
}

// 汇总
function handleInit() {
  let { orgCode,periodCode } = getForm().getFieldsValue();
  const saveMsg = '汇总';
  const msg = '确认要' + saveMsg + '吗？';
  Modal.confirm({
    title: '确认',
    content: msg,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      initSummary({
        orgCode,
        periodCode,
      }).then((res) => {
        // console.log('res', res);
        handleSuccess();
      });
    },
  });
}

/**
 * 提交事件
 */
// function handleSubmit() {
//   Modal.confirm({
//     title: '确认',
//     content: '确认要提交汇总吗？',
//     okText: '确认',
//     cancelText: '取消',
//     onOk: () => {
//       let { periodCode, psnName } = getForm().getFieldsValue();
//       if (!periodCode) {
//         periodCode = dayjs().format('YYYYMM');
//       }
//       handleCommit({ periodCode: periodCode, psnName: psnName }).then((res) => {
//         if (res) {
//           handleSuccess();
//         }
//       });
//     },
//   });
// }
/**
 * 成功回调
 */
function handleSuccess() {
  reload();
}

/**
 * author:lhw
 * description: 批量编辑方法
 * @params: @
 * date: 2023/2/13
 * lastModify: 2023/2/13
 */
function batchEdit() {
  startEdit.value = true;
}

/**
 * author:lhw
 * description: 批量编辑保存
 * @params: @
 * date: 2023/2/13
 * lastModify: 2023/2/13
 */
function batchSave() {
  let records = getDataSource();
  setTimeout(() => {
    // let data = [];
    // records.forEach((item) => {
    //   let obj = {
    //     id: item.id,
    //     hortationScore: item.hortationScore,
    //     grade: item.grade,
    //     finalScore: item.finalScore,
    //   };
    //   data.push(obj);
    // });
    batchUpdate({ datas: records, orgCode: pageParams.orgCodeBase }).then((res) => {
      if (res) {
        handleSuccess();
      }
    }); //保存数据
  }, 500);
  startEdit.value = false;
}

/**
 * author:lhw
 * description: 取消批量编辑
 * @params: @
 * date: 2023/2/13
 * lastModify: 2023/2/13
 */
function editCancel() {
  startEdit.value = false;
  reload();
}
</script>
<style lang="less" scoped>
/deep/.ant-table-wrapper {
  padding: 16px !important;
}

.full-size {
  width: 100%;
  height: 100%;
}

.ant-picker {
  width: 100%;
}

.hit_ul {
  padding-left: 28px;
  list-style: disc;
}

.weight-hint {
  // margin: -4px 0 -2px;
  // padding-top: 5px;

  padding: 8px 0 8px 12px;
  // padding-left: 12px;
  // height: 38px;
  background-color: #f3f3f3;
  border-color: #e3e3e3;
  // line-height: 38px;
  color: #a1a1a1;

  p {
    padding: 0;
    margin: 0;
  }
}

.hint_title {
  font-size: 18px;
}
</style>
